package com.yangcangclub.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.Assert;

/**
 * Json Utlity
 *
 * @author Humn Chou
 * @version 2013-11-8
 *
 */
public final class JsonUtils {

    /**
     * Json转换
     * @param obj
     * @return
     */
    public static String toJsonString(Object obj) {
        Assert.notNull(obj,"the json object is null,please check it!");
        String jsonStr = JSON.toJSONString(
                obj,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.WriteMapNullValue);
        return jsonStr;
    }

    /**
     * Json解析
     * @param jsonStr
     * @return
     */
    public static Object parse(String jsonStr) {
        Assert.notNull(jsonStr, "the json string is null,please check it!");
        return JSON.parse(jsonStr);
    }

    /**
     * Json解析
     * @param jsonStr
     * @return
     */
    public static Object parseObject(String jsonStr,Class<?> clazz) {
        Assert.notNull(jsonStr,"the json string is null,please check it!");
        return JSON.parseObject(jsonStr, clazz);
    }

    /**
     * 转换 byte[]
     * @param obj
     * @return
     */
    public static byte[] toJSONBytes(Object obj) {
        Assert.notNull(obj,"the json object is null,please check it!");
        byte[] jsonByte = JSON.toJSONBytes(
                obj,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteDateUseDateFormat);
        return jsonByte;
    }
}